package com.qf.blog.controller;

import com.qf.blog.commons.response.ResponseResult;
import com.qf.blog.entity.PostPage;
import com.qf.blog.service.IPostService;
import com.qf.blog.vo.PostVo;
import com.qf.blog.vo.SinglePostVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Controller
@RequestMapping ("/post")
public class PostController {
    @Autowired
    private IPostService IPostService;

    @GetMapping ("/action/query")
    public String query(PostPage page, Model model) {
        // 1.查询数据
        PostPage pospage = IPostService.queryPage(page);
        pospage.setPath("/post/action/query");
        // 2.把数据保存到域对象中
        model.addAttribute("page", pospage);
        // 3.跳转到视图
        return "index";
    }

    @GetMapping ("/{id}")
    public String queryById(@PathVariable Integer id,HttpServletRequest request) {
        SinglePostVo singlePostVo = IPostService.queryById(id);
        request.setAttribute("singlePostVo",singlePostVo);
        return "forward:/comment/query?postId="+id;
    }

    @PostMapping ("/publish")
    @ResponseBody
    public ResponseResult query(@RequestBody PostVo  post) {
        IPostService.publish(post);
        return ResponseResult.success();
    }
    @GetMapping ("/query")
    @ResponseBody
    public ResponseResult query(@RequestBody PostPage page) {
        PostPage pospage = IPostService.queryPage(page);
        pospage.setPath("/post/action/query");
        return ResponseResult.success(pospage);
    }
    @PostMapping ("/add")
    @ResponseBody
    public ResponseResult add(@RequestBody PostVo post) {
        boolean flag=IPostService.save(post);
        return ResponseResult.success(flag);
    }
    @PostMapping ("/update")
    @ResponseBody
    public ResponseResult update(@RequestBody PostVo post) {
        boolean flag=IPostService.save(post);
        return ResponseResult.success(flag);
    }
    @PostMapping ("/delete")
    @ResponseBody
    public ResponseResult delete(@RequestBody PostVo post) {
        boolean flag=IPostService.removeById(post);
        return ResponseResult.success(flag);
    }
}

